package flowcontrol.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 场景：多个线程等待一个线程与一个线程等待多个线程结合使用
 */
public class TestCountDownLatch1or2 {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latchStart = new CountDownLatch(1);
        CountDownLatch latchEnd = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int k = i;
            service.submit(() -> {
                System.out.println("员工 " + k + "等待工作");
                try {
                    latchStart.await();
                    System.out.println("员工 " + k + "开始工作");
                    // 模拟员工工作时间
                    Thread.sleep((long) Math.random()*10000);
                    System.out.println("员工 " + k + "工作完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    latchEnd.countDown();
                }
            });
        }
        service.shutdown();
        Thread.sleep(5000);
        // 老板开始下令工作
        System.out.println("所有员工等老板开始下令工作，老板说开始工作");
        latchStart.countDown();

        // 老板等待所有员工工作完成
        latchEnd.await();
        System.out.println("所有员工工作完成了");
    }
}
